package com.lqfan.autoAnswerQ.service.subjectChoiceType.impl;

import com.lqfan.autoAnswerQ.model.subjectChoiceType.SubjectChoiceType;
import com.lqfan.autoAnswerQ.dao.subjectChoiceType.SubjectChoiceTypeMapper;
import com.lqfan.autoAnswerQ.service.subjectChoiceType.ISubjectChoiceTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lqfan
 * @since 2020-04-06
 */
@Service
public class SubjectChoiceTypeServiceImpl extends ServiceImpl<SubjectChoiceTypeMapper, SubjectChoiceType> implements ISubjectChoiceTypeService {

    @Override
    @Transactional
    public boolean saveChoice(String content,String choiceNumber, String subId) {
        SubjectChoiceType choiceType = new SubjectChoiceType();
        choiceType.setContent(content);
        choiceType.setChoiceNumber(choiceNumber);
        choiceType.setSubjectId(subId);
        boolean saveResult = save(choiceType);
        return saveResult;
    }

    @Override
    @Transactional(isolation= Isolation.DEFAULT,propagation= Propagation.REQUIRED,rollbackFor = Exception.class)
    public boolean saveChoice(ArrayList list) {
        try {
            boolean res = batchInsert(list);
            return res;
        }catch (Exception e){
            return false;
        }
//        int i = 1/0;
    }


    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    @Transactional
    public boolean batchInsert(List<SubjectChoiceType> beanList) {
        SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH,false);
        SubjectChoiceTypeMapper mapper = session.getMapper(SubjectChoiceTypeMapper.class);
        try {
            for (int i = 0;i<beanList.size();i++) {
                mapper.insert(beanList.get(i));
                if(i%1000==999 || i==beanList.size()-1) {
                    session.commit();
                    session.clearCache();
                }
            }
        }catch(Exception e) {
            e.printStackTrace();
            session.rollback();
            System.out.println("================================================");
            return false;
        }
        return true;
    }
}
